package com.example.intenttrial.bezier;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;

import com.example.intenttrial.R;

public class BezierActivity extends Activity {
	
	private int pointsCount = 5;
	private DrawerView view;
	private List<Point> supportVertexies;
	private BezierHelper helper;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.screen_bezier);
		mapIU();
		firstInitVertexies(pointsCount);
		setListeners();
	}

	private void mapIU() {
		view = (DrawerView) findViewById(R.id.drawer_view);
	}
	
	private void firstInitVertexies(int count) {
		helper = new BezierHelper();
		supportVertexies = new ArrayList<Point>(count);
		
		Display display = getWindowManager().getDefaultDisplay();
		
		int width = display.getWidth();
		int height = display.getHeight();
		
		Random rand = new Random();
		for(int i = 0; i < count; i++) {
			float x = rand.nextInt(width);
			float y = rand.nextInt(height);
			Point p = new Point(x, y);
			supportVertexies.add(p);
		}
	}
	
	private Point findNeighbour(Point pointToCheck, int delta) {
		for(int i = 0; i < supportVertexies.size(); i++) {
			Point currPoint = supportVertexies.get(i);
			if(Math.abs(currPoint.getX() - pointToCheck.getX()) < delta 
					&& Math.abs(currPoint.getY() - pointToCheck.getY()) < delta) {
				supportVertexies.set(i, pointToCheck);
				return pointToCheck;
			}
		}
		
		return null;
	}
	
	private void setListeners() {
		view.setOnTouchListener(new View.OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				switch(event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					helper.init(supportVertexies);
					view.drawPoints(helper.process(0.02f), helper.getSupportVertexies());
					
				case MotionEvent.ACTION_MOVE:
					
					float x = event.getRawX();
					float y = event.getRawY() - 100;
					Point pointToCheck = new Point(x, y);
					
					if(findNeighbour(pointToCheck, 50) != null) {
						helper.init(supportVertexies);
						view.drawPoints(helper.process(0.02f), helper.getSupportVertexies());
					}
				}
				
				return true;
			}
		});
		
		view.setOnLongClickListener(new View.OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				return false;
			}
		});
	}
	
}
